<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>房贷计算器 - 最优还款方案分析</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 32px;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 14px;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 10px;
        }

        .section-title {
            font-size: 20px;
            color: #667eea;
            margin-bottom: 20px;
            font-weight: bold;
        }

        .input-group {
            display: grid;
            grid-template-columns: 1fr auto 80px;
            gap: 15px;
            align-items: center;
            margin-bottom: 20px;
        }

        .input-group label {
            font-size: 14px;
            color: #333;
            font-weight: 500;
        }

        .input-group input[type="range"] {
            width: 100%;
            height: 8px;
            border-radius: 5px;
            background: #d3d3d3;
            outline: none;
            -webkit-appearance: none;
        }

        .input-group input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #667eea;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }

        .input-group input[type="range"]::-moz-range-thumb {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            background: #667eea;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            border: none;
        }

        .input-group input[type="number"] {
            width: 100%;
            padding: 8px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            text-align: center;
        }

        .input-group input[type="number"]:focus {
            outline: none;
            border-color: #667eea;
        }

        .result-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 15px;
            border-left: 4px solid #667eea;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
        }

        .result-card h3 {
            color: #667eea;
            margin-bottom: 10px;
            font-size: 18px;
        }

        .result-row {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }

        .result-row:last-child {
            border-bottom: none;
        }

        .result-label {
            color: #666;
            font-size: 14px;
        }

        .result-value {
            color: #333;
            font-weight: bold;
            font-size: 15px;
        }

        .result-highlight {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 10px;
            margin-top: 20px;
        }

        .result-highlight h3 {
            color: white;
            margin-bottom: 15px;
        }

        .savings-badge {
            display: inline-block;
            background: rgba(255,255,255,0.2);
            padding: 5px 15px;
            border-radius: 20px;
            margin-top: 10px;
            font-size: 16px;
        }

        .comparison-table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }

        .comparison-table th {
            background: #667eea;
            color: white;
            padding: 12px;
            text-align: left;
            font-size: 14px;
        }

        .comparison-table td {
            padding: 12px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
        }

        .comparison-table tr:hover {
            background: #f8f9fa;
        }

        .best-option {
            color: #10b981;
            font-weight: bold;
        }

        .warning {
            background: #fef3c7;
            border-left: 4px solid #f59e0b;
            padding: 15px;
            border-radius: 5px;
            margin-top: 20px;
        }

        .warning-text {
            color: #92400e;
            font-size: 14px;
        }

        .early-payment-section {
            background: #f0f9ff;
            border: 2px solid #0ea5e9;
        }

        .early-payment-section .section-title {
            color: #0ea5e9;
        }

        .early-payment-active {
            background: #dbeafe;
            padding: 10px;
            border-radius: 5px;
            margin-top: 10px;
        }

        .early-payment-highlight {
            background: linear-gradient(135deg, #0ea5e9 0%, #06b6d4 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-top: 20px;
        }

        .early-payment-highlight h3 {
            color: white;
            margin-bottom: 10px;
        }

        .savings-highlight {
            background: #10b981;
            color: white;
            padding: 15px;
            border-radius: 8px;
            margin-top: 15px;
            font-size: 16px;
            text-align: center;
        }

        .comparison-section {
            margin-top: 30px;
        }

        .comparison-section h3 {
            color: #667eea;
            margin-bottom: 15px;
            font-size: 18px;
        }

        .diff-row {
            background: #fef3c7;
        }

        @media (max-width: 768px) {
            .input-group {
                grid-template-columns: 1fr;
            }

            .comparison-table {
                font-size: 12px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🏠 房贷计算器</h1>
            <p>智能分析最优还款方案 | 实时计算节省利息</p>
        </div>

        <div class="content">
            <!-- 贷款基本信息 -->
            <div class="section">
                <div class="section-title">📋 贷款基本信息</div>

                <div class="input-group">
                    <label>贷款总额 (万元)</label>
                    <input type="range" id="loanAmount" min="0.01" max="1000" step="0.0001" value="100">
                    <input type="number" id="loanAmountInput" min="0.01" max="1000" step="0.000001" value="100">
                </div>

                <div class="input-group">
                    <label>年利率 (%)</label>
                    <input type="range" id="interestRate" min="1" max="10" step="0.01" value="4.3">
                    <input type="number" id="interestRateInput" min="1" max="10" step="0.01" value="4.3">
                </div>

                <div class="input-group">
                    <label>贷款期限 (月)</label>
                    <input type="range" id="loanMonths" min="1" max="360" step="1" value="360">
                    <input type="number" id="loanMonthsInput" min="1" max="360" step="1" value="360">
                </div>
            </div>

            <!-- 收入与还款能力 -->
            <div class="section">
                <div class="section-title">💰 收入与还款能力分析</div>

                <div class="input-group">
                    <label>家庭月收入 (元)</label>
                    <input type="range" id="monthlyIncome" min="3000" max="50000" step="500" value="15000">
                    <input type="number" id="monthlyIncomeInput" min="3000" max="50000" step="500" value="15000">
                </div>

                <div class="result-card">
                    <h3>还款能力评估</h3>
                    <div class="result-row">
                        <span class="result-label">建议月还款额 (收入40%)</span>
                        <span class="result-value" id="recommendedPayment">-</span>
                    </div>
                    <div class="result-row">
                        <span class="result-label">可承受月收入倍数</span>
                        <span class="result-value" id="incomeMultiplier">-</span>
                    </div>
                    <div class="result-row">
                        <span class="result-label">还款压力评级</span>
                        <span class="result-value" id="pressureLevel">-</span>
                    </div>
                </div>
            </div>

            <!-- 还款方案对比 -->
            <div class="section">
                <div class="section-title">📊 还款方案对比分析</div>

                <table class="comparison-table">
                    <thead>
                        <tr>
                            <th>对比项目</th>
                            <th>等额本息</th>
                            <th>等额本金</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>月供 (首月)</td>
                            <td id="equalPayment">-</td>
                            <td id="equalPrincipal">-</td>
                        </tr>
                        <tr>
                            <td>月供 (末月)</td>
                            <td id="equalPaymentEnd">-</td>
                            <td id="equalPrincipalEnd">-</td>
                        </tr>
                        <tr>
                            <td>总还款额</td>
                            <td id="totalEqualPayment">-</td>
                            <td id="totalEqualPrincipal">-</td>
                        </tr>
                        <tr>
                            <td>总利息支出</td>
                            <td id="interestEqualPayment">-</td>
                            <td id="interestEqualPrincipal">-</td>
                        </tr>
                        <tr>
                            <td>利息节省</td>
                            <td>-</td>
                            <td id="interestSavings" class="best-option">-</td>
                        </tr>
                    </tbody>
                </table>

                <div class="result-highlight" id="recommendation">
                    <h3>🎯 最优还款方案推荐</h3>
                    <div id="recommendationText">-</div>
                    <div class="savings-badge" id="savingsBadge" style="display: none;">
                        💰 总共节省利息: <span id="savingsAmount">0</span> 元
                    </div>
                </div>

                <div class="warning" id="incomeWarning" style="display: none;">
                    <span class="warning-text">⚠️ 您的月还款额已超过月收入的50%，建议考虑延长贷款期限或降低贷款金额以降低还款压力。</span>
                </div>
            </div>

            <!-- 详细还款计划 -->
            <div class="section">
                <div class="section-title">📅 详细还款计划 (前12期)</div>
                <div id="paymentSchedule">请输入贷款信息查看详细计划...</div>
            </div>

            <!-- 提前还款功能 -->
            <div class="section early-payment-section" id="earlyPaymentSection" style="display: none;">
                <div class="section-title">💳 提前还款分析</div>

                <div class="input-group">
                    <label>提前还款时间 (第几期)</label>
                    <input type="range" id="earlyPaymentPeriod" min="1" max="360" step="1" value="60">
                    <input type="number" id="earlyPaymentPeriodInput" min="1" max="360" step="1" value="60">
                </div>

                <div class="input-group">
                    <label>提前还款金额 (万元)</label>
                    <input type="range" id="earlyPaymentAmount" min="0" max="100" step="0.0001" value="10">
                    <input type="number" id="earlyPaymentAmountInput" min="0" max="100" step="0.000001" value="10">
                </div>

                <div class="early-payment-active" id="earlyPaymentInfo">
                    <p style="margin: 5px 0; color: #0c4a6e;">
                        <strong>第 <span id="periodDisplay">60</span> 期</strong> 计划还款 <span id="scheduledPayment">-</span> 元
                    </p>
                    <p style="margin: 5px 0; color: #0c4a6e;">
                        本期剩余本金: <span id="remainingPrincipal">-</span> 元
                    </p>
                    <p style="margin: 5px 0; color: #0c4a6e;">
                        提前还款后剩余本金: <span id="newRemainingPrincipal">-</span> 元
                    </p>
                </div>

                <div class="early-payment-highlight" id="earlyPaymentRecommendation">
                    <h3>🎯 提前还款效果分析</h3>
                    <div id="earlyPaymentAnalysis">-</div>
                </div>

                <div class="savings-highlight" id="totalSavings" style="display: none;">
                    💰 提前还款节省利息: <span id="savingsDisplay">0</span> 元
                </div>

                <div class="comparison-section">
                    <h3>📊 提前还款前后对比</h3>
                    <table class="comparison-table">
                        <thead>
                            <tr>
                                <th>对比项目</th>
                                <th>等额本息 (提前还款前)</th>
                                <th>等额本息 (提前还款后)</th>
                                <th>等额本金 (提前还款前)</th>
                                <th>等额本金 (提前还款后)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>
                                <td>月供</td>
                                <td id="epEqPayBefore">-</td>
                                <td id="epEqPayAfter" class="best-option">-</td>
                                <td id="epEqPrinBefore">-</td>
                                <td id="epEqPrinAfter" class="best-option">-</td>
                            </tr>
                            <tr>
                                <td>总还款额</td>
                                <td id="epTotalEqPayBefore">-</td>
                                <td id="epTotalEqPayAfter" class="best-option">-</td>
                                <td id="epTotalEqPrinBefore">-</td>
                                <td id="epTotalEqPrinAfter" class="best-option">-</td>
                            </tr>
                            <tr>
                                <td>总利息支出</td>
                                <td id="epInterestEqPayBefore">-</td>
                                <td id="epInterestEqPayAfter" class="best-option">-</td>
                                <td id="epInterestEqPrinBefore">-</td>
                                <td id="epInterestEqPrinAfter" class="best-option">-</td>
                            </tr>
                            <tr class="diff-row">
                                <td><strong>利息节省</strong></td>
                                <td>-</td>
                                <td id="epSavingsEqPay" class="best-option">-</td>
                                <td>-</td>
                                <td id="epSavingsEqPrin" class="best-option">-</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <div class="comparison-section">
                    <h3>📅 提前还款后详细计划 (前12期)</h3>
                    <div id="earlyPaymentSchedule">设置提前还款参数查看详细计划...</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 房贷计算核心函数
        class LoanCalculator {
            // 等额本息计算
            static calculateEqualPayment(principal, annualRate, months) {
                const monthlyRate = annualRate / 12;
                const totalAmount = principal * monthlyRate * Math.pow(1 + monthlyRate, months) /
                                 (Math.pow(1 + monthlyRate, months) - 1);
                const totalPayment = totalAmount * months;
                const totalInterest = totalPayment - principal;
                return { monthlyPayment: totalAmount, totalPayment, totalInterest };
            }

            // 等额本金计算
            static calculateEqualPrincipal(principal, annualRate, months) {
                const monthlyRate = annualRate / 12;
                const monthlyPrincipal = principal / months;
                const result = [];
                let remainingPrincipal = principal;
                let totalInterest = 0;

                for (let i = 0; i < months; i++) {
                    const interest = remainingPrincipal * monthlyRate;
                    const payment = monthlyPrincipal + interest;
                    totalInterest += interest;
                    remainingPrincipal -= monthlyPrincipal;

                    if (i < 12) {
                        result.push({
                            period: i + 1,
                            payment: payment,
                            principal: monthlyPrincipal,
                            interest: interest,
                            remaining: Math.max(0, remainingPrincipal)
                        });
                    }
                }

                const totalPayment = principal + totalInterest;
                return {
                    schedule: result,
                    firstPayment: result[0]?.payment || 0,
                    lastPayment: result[months - 1]?.payment || 0,
                    totalPayment,
                    totalInterest
                };
            }

            // 还款能力分析
            static analyzePaymentCapacity(monthlyIncome, monthlyPayment) {
                const ratio = monthlyPayment / monthlyIncome;
                let level, multiplier;

                if (ratio < 0.3) {
                    level = '轻松';
                    multiplier = '30%以内';
                } else if (ratio < 0.4) {
                    level = '合理';
                    multiplier = '30%-40%';
                } else if (ratio < 0.5) {
                    level = '适中';
                    multiplier = '40%-50%';
                } else {
                    level = '较重';
                    multiplier = '超过50%';
                }

                return { ratio, level, multiplier, recommended: monthlyIncome * 0.4 };
            }

            // 等额本息提前还款计算
            static calculateEqualPaymentWithEarlyPayment(principal, annualRate, months, earlyPaymentPeriod, earlyPaymentAmount) {
                const monthlyRate = annualRate / 12;
                const totalAmount = principal * monthlyRate * Math.pow(1 + monthlyRate, months) /
                                 (Math.pow(1 + monthlyRate, months) - 1);

                // 生成完整还款计划
                let remainingPrincipal = principal;
                let totalInterest = 0;
                const schedule = [];
                let scheduledPaymentAtPeriod = 0;

                for (let i = 0; i < months; i++) {
                    const interest = remainingPrincipal * monthlyRate;

                    if (i + 1 === earlyPaymentPeriod) {
                        // 提前还款期
                        const currentPayment = totalAmount;
                        const principalPart = currentPayment - interest;
                        remainingPrincipal -= principalPart;
                        scheduledPaymentAtPeriod = currentPayment;

                        // 提前还款
                        const earlyPayment = Math.min(earlyPaymentAmount, remainingPrincipal);
                        remainingPrincipal -= earlyPayment;

                        schedule.push({
                            period: i + 1,
                            payment: currentPayment + earlyPayment,
                            principal: principalPart + earlyPayment,
                            interest: interest,
                            remaining: Math.max(0, remainingPrincipal),
                            earlyPayment: earlyPayment
                        });

                        totalInterest += interest;
                    } else if (remainingPrincipal > 0) {
                        // 重新计算剩余期数的月供
                        const remainingMonths = months - i - 1;
                        let newPayment = totalAmount;
                        if (remainingMonths > 0) {
                            newPayment = remainingPrincipal * monthlyRate * Math.pow(1 + monthlyRate, remainingMonths) /
                                       (Math.pow(1 + monthlyRate, remainingMonths) - 1);
                        } else {
                            newPayment = remainingPrincipal + interest;
                        }

                        const principalPart = newPayment - interest;
                        remainingPrincipal -= principalPart;

                        schedule.push({
                            period: i + 1,
                            payment: newPayment,
                            principal: principalPart,
                            interest: interest,
                            remaining: Math.max(0, remainingPrincipal)
                        });

                        totalInterest += interest;
                    }
                }

                // 重新计算剩余期数的月供
                const remainingMonths = months - earlyPaymentPeriod;
                let newMonthlyPayment = 0;
                if (remainingMonths > 0 && remainingPrincipal > 0) {
                    newMonthlyPayment = remainingPrincipal * monthlyRate * Math.pow(1 + monthlyRate, remainingMonths) /
                                      (Math.pow(1 + monthlyRate, remainingMonths) - 1);
                }

                const totalPayment = principal + totalInterest + earlyPaymentAmount;
                return {
                    schedule,
                    monthlyPayment: newMonthlyPayment,
                    firstPayment: totalAmount,
                    lastPayment: newMonthlyPayment,
                    totalPayment,
                    totalInterest,
                    scheduledPaymentAtPeriod,
                    remainingPrincipalBeforeEP: remainingPrincipal + earlyPaymentAmount,
                    remainingPrincipalAfterEP: remainingPrincipal
                };
            }

            // 等额本金提前还款计算
            static calculateEqualPrincipalWithEarlyPayment(principal, annualRate, months, earlyPaymentPeriod, earlyPaymentAmount) {
                const monthlyRate = annualRate / 12;
                const schedule = [];
                let totalInterest = 0;
                let remainingPrincipal = principal;
                let scheduledPaymentAtPeriod = 0;
                let remainingPrincipalBeforeEP = 0;

                for (let i = 0; i < months; i++) {
                    const interest = remainingPrincipal * monthlyRate;

                    if (i + 1 === earlyPaymentPeriod) {
                        // 提前还款期
                        const monthlyPrincipal = principal / months;
                        scheduledPaymentAtPeriod = monthlyPrincipal + interest;
                        remainingPrincipalBeforeEP = remainingPrincipal;
                        remainingPrincipal -= monthlyPrincipal;
                        totalInterest += interest;

                        // 提前还款
                        const earlyPayment = Math.min(earlyPaymentAmount, remainingPrincipal);
                        remainingPrincipal -= earlyPayment;

                        schedule.push({
                            period: i + 1,
                            payment: scheduledPaymentAtPeriod + earlyPayment,
                            principal: monthlyPrincipal + earlyPayment,
                            interest: interest,
                            remaining: Math.max(0, remainingPrincipal),
                            earlyPayment: earlyPayment
                        });
                    } else if (remainingPrincipal > 0) {
                        // 提前还款后，重新分摊剩余本金到剩余期数
                        const remainingMonths = months - i - 1;
                        let newMonthlyPrincipal = 0;
                        if (remainingMonths > 0) {
                            newMonthlyPrincipal = remainingPrincipal / remainingMonths;
                        } else {
                            newMonthlyPrincipal = remainingPrincipal;
                        }

                        const payment = newMonthlyPrincipal + interest;
                        remainingPrincipal -= newMonthlyPrincipal;
                        totalInterest += interest;

                        schedule.push({
                            period: i + 1,
                            payment: payment,
                            principal: newMonthlyPrincipal,
                            interest: interest,
                            remaining: Math.max(0, remainingPrincipal)
                        });
                    }
                }

                // 重新计算剩余期数的月供
                const remainingMonths = months - earlyPaymentPeriod;
                let newMonthlyPrincipal = 0;
                let newMonthlyPayment = 0;
                if (remainingMonths > 0 && remainingPrincipal > 0) {
                    // 重新分摊剩余本金到剩余期数
                    newMonthlyPrincipal = remainingPrincipal / remainingMonths;
                    // 第一期还款（利息+本金）
                    newMonthlyPayment = newMonthlyPrincipal + (remainingPrincipal * monthlyRate);
                }

                const totalPayment = principal + totalInterest + earlyPaymentAmount;
                return {
                    schedule,
                    firstPayment: schedule[0]?.payment || 0,
                    lastPayment: newMonthlyPayment,
                    monthlyPayment: newMonthlyPayment,
                    totalPayment,
                    totalInterest,
                    scheduledPaymentAtPeriod,
                    remainingPrincipalBeforeEP: remainingPrincipalBeforeEP,
                    remainingPrincipalAfterEP: remainingPrincipal
                };
            }
        }

        // 获取DOM元素
        const elements = {
            loanAmount: document.getElementById('loanAmount'),
            loanAmountInput: document.getElementById('loanAmountInput'),
            interestRate: document.getElementById('interestRate'),
            interestRateInput: document.getElementById('interestRateInput'),
            loanMonths: document.getElementById('loanMonths'),
            loanMonthsInput: document.getElementById('loanMonthsInput'),
            monthlyIncome: document.getElementById('monthlyIncome'),
            monthlyIncomeInput: document.getElementById('monthlyIncomeInput'),
            recommendedPayment: document.getElementById('recommendedPayment'),
            incomeMultiplier: document.getElementById('incomeMultiplier'),
            pressureLevel: document.getElementById('pressureLevel'),
            equalPayment: document.getElementById('equalPayment'),
            equalPaymentEnd: document.getElementById('equalPaymentEnd'),
            equalPrincipal: document.getElementById('equalPrincipal'),
            equalPrincipalEnd: document.getElementById('equalPrincipalEnd'),
            totalEqualPayment: document.getElementById('totalEqualPayment'),
            totalEqualPrincipal: document.getElementById('totalEqualPrincipal'),
            interestEqualPayment: document.getElementById('interestEqualPayment'),
            interestEqualPrincipal: document.getElementById('interestEqualPrincipal'),
            interestSavings: document.getElementById('interestSavings'),
            recommendationText: document.getElementById('recommendationText'),
            savingsBadge: document.getElementById('savingsBadge'),
            savingsAmount: document.getElementById('savingsAmount'),
            incomeWarning: document.getElementById('incomeWarning'),
            paymentSchedule: document.getElementById('paymentSchedule'),
            // 提前还款相关元素
            earlyPaymentSection: document.getElementById('earlyPaymentSection'),
            earlyPaymentPeriod: document.getElementById('earlyPaymentPeriod'),
            earlyPaymentPeriodInput: document.getElementById('earlyPaymentPeriodInput'),
            earlyPaymentAmount: document.getElementById('earlyPaymentAmount'),
            earlyPaymentAmountInput: document.getElementById('earlyPaymentAmountInput'),
            periodDisplay: document.getElementById('periodDisplay'),
            scheduledPayment: document.getElementById('scheduledPayment'),
            remainingPrincipal: document.getElementById('remainingPrincipal'),
            newRemainingPrincipal: document.getElementById('newRemainingPrincipal'),
            earlyPaymentAnalysis: document.getElementById('earlyPaymentAnalysis'),
            totalSavings: document.getElementById('totalSavings'),
            savingsDisplay: document.getElementById('savingsDisplay'),
            epEqPayBefore: document.getElementById('epEqPayBefore'),
            epEqPayAfter: document.getElementById('epEqPayAfter'),
            epEqPrinBefore: document.getElementById('epEqPrinBefore'),
            epEqPrinAfter: document.getElementById('epEqPrinAfter'),
            epTotalEqPayBefore: document.getElementById('epTotalEqPayBefore'),
            epTotalEqPayAfter: document.getElementById('epTotalEqPayAfter'),
            epTotalEqPrinBefore: document.getElementById('epTotalEqPrinBefore'),
            epTotalEqPrinAfter: document.getElementById('epTotalEqPrinAfter'),
            epInterestEqPayBefore: document.getElementById('epInterestEqPayBefore'),
            epInterestEqPayAfter: document.getElementById('epInterestEqPayAfter'),
            epInterestEqPrinBefore: document.getElementById('epInterestEqPrinBefore'),
            epInterestEqPrinAfter: document.getElementById('epInterestEqPrinAfter'),
            epSavingsEqPay: document.getElementById('epSavingsEqPay'),
            epSavingsEqPrin: document.getElementById('epSavingsEqPrin'),
            earlyPaymentSchedule: document.getElementById('earlyPaymentSchedule')
        };

        // 同步滑块和输入框
        function syncSliderAndInput(slider, input, callback = calculate) {
            slider.addEventListener('input', () => {
                input.value = slider.value;
                callback();
            });
            input.addEventListener('input', () => {
                slider.value = input.value;
                callback();
            });
        }

        // 格式化数字
        function formatNumber(num) {
            return num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }

        // 格式化货币
        function formatCurrency(num) {
            return formatNumber(num) + ' 元';
        }

        // 计算并更新界面
        function calculate() {
            const loanAmount = parseFloat(elements.loanAmount.value) * 10000;
            const annualRate = parseFloat(elements.interestRate.value) / 100;
            const months = parseInt(elements.loanMonths.value);
            const monthlyIncome = parseFloat(elements.monthlyIncome.value);

            // 等额本息
            const equalPayment = LoanCalculator.calculateEqualPayment(loanAmount, annualRate, months);

            // 等额本金
            const equalPrincipal = LoanCalculator.calculateEqualPrincipal(loanAmount, annualRate, months);

            // 还款能力分析
            const capacity = LoanCalculator.analyzePaymentCapacity(monthlyIncome, equalPayment.monthlyPayment);

            // 更新还款能力
            elements.recommendedPayment.textContent = formatCurrency(capacity.recommended);
            elements.incomeMultiplier.textContent = capacity.multiplier;
            elements.pressureLevel.textContent = capacity.level;

            // 更新方案对比
            elements.equalPayment.textContent = formatCurrency(equalPayment.monthlyPayment);
            elements.equalPrincipal.textContent = formatCurrency(equalPrincipal.firstPayment);
            elements.equalPaymentEnd.textContent = formatCurrency(equalPayment.monthlyPayment);
            elements.equalPrincipalEnd.textContent = formatCurrency(equalPrincipal.lastPayment);
            elements.totalEqualPayment.textContent = formatCurrency(equalPayment.totalPayment);
            elements.totalEqualPrincipal.textContent = formatCurrency(equalPrincipal.totalPayment);
            elements.interestEqualPayment.textContent = formatCurrency(equalPayment.totalInterest);
            elements.interestEqualPrincipal.textContent = formatCurrency(equalPrincipal.totalInterest);

            const interestSaved = equalPayment.totalInterest - equalPrincipal.totalInterest;
            elements.interestSavings.textContent = formatCurrency(interestSaved);

            // 推荐方案
            let recommendation = '';
            if (equalPrincipal.totalInterest < equalPayment.totalInterest) {
                const savingsPercent = (interestSaved / equalPayment.totalInterest * 100).toFixed(1);
                recommendation = `推荐选择<b class="best-option">等额本金</b>方式，总利息可节省 ${formatNumber(interestSaved)} 元 (${savingsPercent}%)。虽然前期还款压力较大，但长期来看更划算。`;
                elements.savingsAmount.textContent = formatNumber(interestSaved);
                elements.savingsBadge.style.display = 'block';
            } else {
                recommendation = '等额本息和等额本金两种方式总利息相同。';
                elements.savingsBadge.style.display = 'none';
            }
            elements.recommendationText.innerHTML = recommendation;

            // 还款压力警告
            if (capacity.ratio > 0.5) {
                elements.incomeWarning.style.display = 'block';
            } else {
                elements.incomeWarning.style.display = 'none';
            }

            // 生成还款计划
            generatePaymentSchedule(equalPrincipal.schedule);

            // 计算提前还款
            elements.earlyPaymentPeriod.max = months;
            elements.earlyPaymentPeriodInput.max = months;
            elements.earlyPaymentSection.style.display = 'block';
            calculateEarlyPayment();
        }

        // 生成还款计划
        function generatePaymentSchedule(schedule) {
            let html = '<table class="comparison-table"><thead><tr><th>期数</th><th>月供</th><th>本金</th><th>利息</th><th>剩余本金</th></tr></thead><tbody>';

            schedule.forEach(item => {
                let rowClass = '';
                if (item.earlyPayment > 0) {
                    rowClass = 'style="background: #dbeafe; font-weight: bold;"';
                }
                html += `<tr ${rowClass}>
                    <td>${item.period}</td>
                    <td>${formatCurrency(item.payment)}${item.earlyPayment > 0 ? '<br><small style="color: #0ea5e9;">含提前还款 ' + formatCurrency(item.earlyPayment) + '</small>' : ''}</td>
                    <td>${formatCurrency(item.principal)}</td>
                    <td>${formatCurrency(item.interest)}</td>
                    <td>${formatCurrency(item.remaining)}</td>
                </tr>`;
            });

            html += '</tbody></table>';
            elements.paymentSchedule.innerHTML = html;
        }

        // 计算提前还款
        function calculateEarlyPayment() {
            const loanAmount = parseFloat(elements.loanAmount.value) * 10000;
            const annualRate = parseFloat(elements.interestRate.value) / 100;
            const months = parseInt(elements.loanMonths.value);
            const earlyPaymentPeriod = parseInt(elements.earlyPaymentPeriod.value);
            const earlyPaymentAmount = parseFloat(elements.earlyPaymentAmount.value) * 10000;

            // 等额本息提前还款
            const epEqualPayment = LoanCalculator.calculateEqualPaymentWithEarlyPayment(
                loanAmount, annualRate, months, earlyPaymentPeriod, earlyPaymentAmount
            );

            // 等额本金提前还款
            const epEqualPrincipal = LoanCalculator.calculateEqualPrincipalWithEarlyPayment(
                loanAmount, annualRate, months, earlyPaymentPeriod, earlyPaymentAmount
            );

            // 原始等额本息
            const originalEqualPayment = LoanCalculator.calculateEqualPayment(loanAmount, annualRate, months);
            const originalEqualPrincipal = LoanCalculator.calculateEqualPrincipal(loanAmount, annualRate, months);

            // 更新提前还款信息
            elements.periodDisplay.textContent = earlyPaymentPeriod;
            elements.scheduledPayment.textContent = formatNumber(epEqualPayment.scheduledPaymentAtPeriod);
            elements.remainingPrincipal.textContent = formatNumber(epEqualPayment.remainingPrincipalBeforeEP);
            elements.newRemainingPrincipal.textContent = formatNumber(epEqualPayment.remainingPrincipalAfterEP);

            // 更新提前还款对比
            elements.epEqPayBefore.textContent = formatCurrency(originalEqualPayment.monthlyPayment);
            elements.epEqPayAfter.textContent = epEqualPayment.monthlyPayment > 0 ? formatCurrency(epEqualPayment.monthlyPayment) : '已还清';
            elements.epEqPrinBefore.textContent = formatCurrency(originalEqualPrincipal.firstPayment);
            elements.epEqPrinAfter.textContent = epEqualPrincipal.monthlyPayment > 0 ? formatCurrency(epEqualPrincipal.monthlyPayment) : '已还清';

            elements.epTotalEqPayBefore.textContent = formatCurrency(originalEqualPayment.totalPayment);
            elements.epTotalEqPayAfter.textContent = formatCurrency(epEqualPayment.totalPayment);
            elements.epTotalEqPrinBefore.textContent = formatCurrency(originalEqualPrincipal.totalPayment);
            elements.epTotalEqPrinAfter.textContent = formatCurrency(epEqualPrincipal.totalPayment);

            elements.epInterestEqPayBefore.textContent = formatCurrency(originalEqualPayment.totalInterest);
            elements.epInterestEqPayAfter.textContent = formatCurrency(epEqualPayment.totalInterest);
            elements.epInterestEqPrinBefore.textContent = formatCurrency(originalEqualPrincipal.totalInterest);
            elements.epInterestEqPrinAfter.textContent = formatCurrency(epEqualPrincipal.totalInterest);

            // 利息节省
            const epSavingsEqPay = originalEqualPayment.totalInterest - epEqualPayment.totalInterest;
            const epSavingsEqPrin = originalEqualPrincipal.totalInterest - epEqualPrincipal.totalInterest;
            elements.epSavingsEqPay.textContent = epSavingsEqPay > 0 ? formatCurrency(epSavingsEqPay) : '0 元';
            elements.epSavingsEqPrin.textContent = epSavingsEqPrin > 0 ? formatCurrency(epSavingsEqPrin) : '0 元';

            // 提前还款效果分析
            const totalSavings = Math.max(epSavingsEqPay, epSavingsEqPrin);
            if (totalSavings > 0) {
                const betterMethod = epSavingsEqPay > epSavingsEqPrin ? '等额本息' : '等额本金';
                elements.earlyPaymentAnalysis.innerHTML = `
                    建议选择 <strong>${betterMethod}</strong> 提前还款方式。
                    <br>通过提前还款，可以节省 <strong>${formatNumber(totalSavings)}</strong> 元利息。
                    <br>提前还款 <strong>${earlyPaymentPeriod} 期</strong> 后，月供将 <strong>${epEqualPayment.monthlyPayment < originalEqualPayment.monthlyPayment ? '减少' : '调整'}</strong>。
                `;
                elements.savingsDisplay.textContent = formatNumber(totalSavings);
                elements.totalSavings.style.display = 'block';
            } else {
                elements.earlyPaymentAnalysis.textContent = '当前参数下，提前还款不会产生利息节省。';
                elements.totalSavings.style.display = 'none';
            }

            // 生成提前还款后的还款计划（显示包含提前还款期的12期）
            generateEarlyPaymentSchedule(epEqualPayment.schedule);
        }

        // 生成提前还款后的还款计划
        function generateEarlyPaymentSchedule(schedule) {
            let html = '<table class="comparison-table"><thead><tr><th>期数</th><th>月供</th><th>本金</th><th>利息</th><th>剩余本金</th></tr></thead><tbody>';

            schedule.slice(0, 12).forEach(item => {
                let rowClass = '';
                if (item.earlyPayment > 0) {
                    rowClass = 'style="background: #dbeafe; font-weight: bold;"';
                }
                html += `<tr ${rowClass}>
                    <td>${item.period}</td>
                    <td>${formatCurrency(item.payment)}${item.earlyPayment > 0 ? '<br><small style="color: #0ea5e9;">含提前还款 ' + formatCurrency(item.earlyPayment) + '</small>' : ''}</td>
                    <td>${formatCurrency(item.principal)}</td>
                    <td>${formatCurrency(item.interest)}</td>
                    <td>${formatCurrency(item.remaining)}</td>
                </tr>`;
            });

            html += '</tbody></table>';
            elements.earlyPaymentSchedule.innerHTML = html;
        }

        // 初始化
        function init() {
            // 同步所有滑块和输入框
            syncSliderAndInput(elements.loanAmount, elements.loanAmountInput);
            syncSliderAndInput(elements.interestRate, elements.interestRateInput);
            syncSliderAndInput(elements.loanMonths, elements.loanMonthsInput);
            syncSliderAndInput(elements.monthlyIncome, elements.monthlyIncomeInput);
            syncSliderAndInput(elements.earlyPaymentPeriod, elements.earlyPaymentPeriodInput, calculateEarlyPayment);
            syncSliderAndInput(elements.earlyPaymentAmount, elements.earlyPaymentAmountInput, calculateEarlyPayment);

            // 初始计算
            calculate();
        }

        // 启动应用
        init();
    </script>
</body>
</html>
